<template>
    <MatchView v-if="websocketStore.pk.status === 'matching' && socketReady" />
    <PvpPlayground v-if="websocketStore.pk.status === 'playing' && socketReady" />
</template>

<script setup>
    import MatchView from '@/views/game/playground/pvp/match/MatchView.vue'
    import PvpPlayground from '@/views/game/playground/pvp/PvPPlayground.vue'
    import { onMounted, onUnmounted, ref } from 'vue'
    import { useUserStore } from '@/stores/user'
    import { useWebsocketStore } from '@/stores/websocket'

    const userStore = useUserStore()
    const websocketStore = useWebsocketStore()
    const socketUrl = `ws://127.0.0.1:8080/websocket/${userStore.token}`
    const socketReady = ref(false)

    let socket = null

    onMounted(() => {
        socket = new WebSocket(socketUrl)

        socket.onopen = () => {
            console.log('websocket连接成功')
            websocketStore.updateSocket(socket)
            socketReady.value = true
        }

        socket.onclose = () => {
            console.log('websocket连接关闭')
            socketReady.value = false
        }
    })

    onUnmounted(() => {
        socket.close()
    })
</script>

<style scoped></style>
